﻿using Microsoft.Extensions.Options;
using MimeKit;
using MailKit.Net.Smtp;
using ZH.Infrastructure.Attr;
using ZH.Service.Interface;
using MailKit.Security;

namespace ZH.Service.Instance
{
    [Inject_]
    public class Email_Service : I_Email_Service
    {
        private readonly EmailSettings _emailSettings;

        public Email_Service(IOptions<EmailSettings> emailSettings)
        {
            _emailSettings = emailSettings.Value;
        }
        public async Task<string> SendVerificationCodeAsync(string toEmail)
        {
            // 1. 生成6位数字验证码
            var verificationCode = new Random().Next(100000, 999999).ToString();
            // 2. 构建邮件内容
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(
                _emailSettings.SenderName,
                _emailSettings.SenderEmail
            ));
            message.To.Add(new MailboxAddress("", toEmail));
            message.Subject = "您的验证码";
            message.Body = new TextPart("plain")
            {
                Text = $"您的验证码是：{verificationCode}，有效期5分钟。请勿向他人泄露。"
            };

            // 3. 发送邮件
            using (var client = new SmtpClient())
            {
                try
                {
                    // 连接SMTP服务器（QQ邮箱示例）
                    await client.ConnectAsync(
                        _emailSettings.SmtpServer,
                        _emailSettings.SmtpPort,
                       SecureSocketOptions.StartTls
                    );
                    // 身份验证
                    await client.AuthenticateAsync(
                        _emailSettings.SmtpUsername,
                        _emailSettings.SmtpPassword
                    );
                    // 发送邮件
                    await client.SendAsync(message);
                    await client.DisconnectAsync(true);

                    return verificationCode; // 返回验证码用于缓存
                }
                catch (Exception ex)
                {
                    throw new Exception($"发送失败：{ex.Message}");
                }
            }
        }
    }

    // 邮件设置模型
    public class EmailSettings
    {
        public string SmtpServer { get; set; }
        public int SmtpPort { get; set; }
        public string SmtpUsername { get; set; }
        public string SmtpPassword { get; set; }
        public string SenderName { get; set; }
        public string SenderEmail { get; set; }
    }
}
